package wedaex.remote;

import java.io.IOException;
import java.io.PrintStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class JsonServlet extends HttpServlet {
	protected static Log log = LogFactory.getLog(JsonServlet.class);
	
	private static Pattern keyPattern = Pattern.compile("/([a-zA-Z0-9]+)\\.ajax",
			Pattern.CASE_INSENSITIVE|Pattern.DOTALL);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		dispatch(request, response);
	}
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		dispatch(request, response);
	}

	/**
	 * Dispatch to different handler based on the path
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	protected void dispatch(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String handlerName = extractHandlerName(request.getRequestURI());
		JsonHandler handler = JsonHandler.getInstance(handlerName);
		if(handler==null) {
			response.getOutputStream().println("No such request handler: " + handlerName);
			response.getOutputStream().close();
			return;
		}
		try {
			IOUtils.write(handler.handle(request, response), response.getOutputStream(), "UTF-8");
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			e.printStackTrace(new PrintStream(response.getOutputStream()));
		}
		response.getOutputStream().close();
	}
	
	private String extractHandlerName(String requestURI) {
		Matcher m = keyPattern.matcher(requestURI);
		if(m.find())
			return m.group(1);
		else
			return null;
	}
}
